//
//  DownloadManager.m
//  first app
//
//  Created by 林 小明 on 14-7-10.
//
//

#import "DownloadManager.h"
#import "AsyncDownload.h"

@implementation DownloadManager

+ (DownloadManager *)sharedSingleton
{
    static DownloadManager *sharedSingleton;
    
    @synchronized(self)
    {
        if (!sharedSingleton)
            sharedSingleton = [[DownloadManager alloc] init];
        
        return sharedSingleton;
    }
}

- (DownloadManager *) init
{
    downloadMap = [[NSMutableDictionary alloc] initWithCapacity:20];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getDownloadProgressInfo:) name:@"Notification_DownloadProgress" object:nil];
    return [super init];
}

- (void) downloadUrl:dirpath fileName:filename URL:url
{
    AsyncDownload* download = (AsyncDownload*)[downloadMap objectForKey:url];
    if( !download )
    {
        download = [[AsyncDownload alloc] initWithDownloadFile:filename Path:dirpath Url:url];
        [downloadMap setObject:download forKey:url];
    }
    
    [download startDownload];
}

- (void) stopDownload:url
{
    AsyncDownload* download = (AsyncDownload*)[downloadMap objectForKey:url];
    if( download )
    {
        [download stopDownload];
        [downloadMap removeObjectForKey:url];
    }
}

- (void) getDownloadProgressInfo: (NSNotification*) aNotification
{
    NSMutableDictionary *downloadInfo = [aNotification object];
    NSString* downlaod_url = [downloadInfo objectForKey:@"downloadurl"];
    int downlaod_status = [[downloadInfo objectForKey:@"downloadstatus"] intValue];
    
    if( downlaod_status == kDownloadStatusFinish )
    {
        AsyncDownload* download = (AsyncDownload*)[downloadMap objectForKey:downlaod_url];
        if( download )
        {
            [download stopDownload];
            [downloadMap removeObjectForKey:downlaod_url];
        }
    }
}
@end
